#!/etc/bin/env python2.6

import os
import ebook
import Stemmer
import pickle

class invIndex:
    def __init__(self):
        self.fileNames = []
        self.idx = {}
        self.ruStemmer = Stemmer.Stemmer('russian')
        self.enStemmer = Stemmer.Stemmer('english')

    def addWordToIndex(self, word, bookID):
        word = word.lower()
        word = self.enStemmer.stemWord(word)
        if word not in self.idx:
            item = [word, [bookID]]
            self.idx.update([item])
        else:
            self.idx[word].append(bookID)

    def addEBookToIndex(self, book):
        self.fileNames.append(book.fileName)
        bookID = len(self.fileNames) - 1

        print 'book.fileName=', book.fileName
        print 'book.title=', book.title
        print 'book.author=', book.creator
        print 'bookID=', bookID

        words = book.title.split(' ')
        for word in words:
            self.addWordToIndex(word, bookID)

        words = book.creator.split(' ')
        for word in words:
            self.addWordToIndex(word, bookID)

    def search(self, stroka):
        bookIDs = []
        words = stroka.split(' ')
        for word in words:
            ids = self.idx.get(word, [])
            for id in ids:
                bookIDs.append(id)

        res = []
        for id in bookIDs:
            book = ebook.ebook(self.fileNames[id])
            res.append(book)

        return res

def buildInvIndex(libraryDir):
    idx = invIndex()
    fnames = ebook.getListOfEBookFiles(libraryDir)
    for fname in fnames:
        book = ebook.ebook(fname)
        idx.addEBookToIndex(book)

    for (key, value) in idx.idx.iteritems():
        print key, value

    return idx

def storeIndexToFile(idx, fname):
    file = open(fname, 'w')
    fileNamesCnt = len(idx.fileNames)
    file.write(str(fileNamesCnt))
    file.write('\n')
    cnt = 0
    for f in idx.fileNames:
        file.write(str(cnt))
        file.write('\t')
        file.write(f)
        file.write('\n')
        cnt += 1

    idxItems = idx.idx.iteritems()
    idxItemsCnt = len(idxItems)
    file.write(str(idxItemsCnt))
    for (key, value) in idxItems:
        file.write(key)
        file.write('\t')
        file.write(repr(value))
        file.write('\n')

def loadIndexFromFile(fname):
    file = open(fname, 'r')

